package org.spiderflow.redis.executor.shape;

import java.util.Map;

import org.apache.commons.lang3.math.NumberUtils;
import org.spiderflow.context.SpiderContext;
import org.spiderflow.executor.ShapeExecutor;
import org.spiderflow.model.Shape;
import org.spiderflow.model.SpiderNode;
import org.spiderflow.redis.utils.RedisUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisExecutor implements ShapeExecutor{
	
	public static final String DATABASE_INDEX = "database";
	
	public static final String REDIS_HOST = "host";
	
	public static final String REDIS_PORT = "port";
	
	public static final String REDIS_PASSWORD = "password";
	
	public static final String REDIS_POOL_MAX_ACTIVE = "poolMaxActive";

	public static final String REDIS_POOL_MAX_IDLE = "poolMaxIdle";
	
	public static final String REDIS_POOL_MIN_IDLE = "poolMinIdle";
	
	public static final String REDIS_CONTEXT_KEY = "$redis_";
	
	@Override
	public String supportShape() {
		return "redis";
	}
	
	@Override
	public Shape shape() {
		Shape shape = new Shape();
		shape.setImage("");
		shape.setLabel("Redis");
		shape.setName("redis");
		shape.setTitle("Redis");
		return shape;
	}

	@Override
	public void execute(SpiderNode node, SpiderContext context, Map<String, Object> variables) {
		int database = NumberUtils.toInt(node.getStringJsonValue(DATABASE_INDEX),0);
		String host = node.getStringJsonValue(REDIS_HOST);
		String password = node.getStringJsonValue(REDIS_PASSWORD);
		int port = NumberUtils.toInt(node.getStringJsonValue(REDIS_PORT),6379);
		int poolMaxActive = NumberUtils.toInt(node.getStringJsonValue(REDIS_POOL_MAX_ACTIVE),8);
		int poolMaxIdle = NumberUtils.toInt(node.getStringJsonValue(REDIS_POOL_MAX_IDLE),8);
		int poolMinIdle = NumberUtils.toInt(node.getStringJsonValue(REDIS_POOL_MIN_IDLE),0);
		StringRedisTemplate redisTemplate = RedisUtils.createRedisTemplate(host, port, password, database, poolMaxActive, poolMaxIdle, poolMinIdle);
		context.put(REDIS_CONTEXT_KEY + node.getNodeId(), redisTemplate);
	}

}
